package com.xjtu.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xjtu.constant.JwtClaimsConstant;
import com.xjtu.constant.MessageConstant;
import com.xjtu.constant.PasswordConstant;
import com.xjtu.dto.*;
import com.xjtu.entity.User;
import com.xjtu.exception.BaseException;
import com.xjtu.exception.PasswordErrorException;
import com.xjtu.mapper.UserMapper;
import com.xjtu.properties.JwtProperties;
import com.xjtu.result.PageResult;
import com.xjtu.service.UserService;
import com.xjtu.utils.JwtUtil;
import com.xjtu.vo.UserLoginVo;
import com.xjtu.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

// Spring IOC容器，持久化对象
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public UserLoginVo login(UserLoginDTO userLoginDTO) {
        // 首先是查看是否有这个人
        User user = userMapper.queryByPhone(userLoginDTO.getPhoneNumber());
        // 有这个人，看密码是否正确
        if(Objects.isNull(user)){
            // 这个人不存在
            throw new BaseException("用户不存在");
        }
        // 这里，用户存在，判断密码是否正确
        // 给用户密码解密
        String passwordIn = DigestUtils.md5DigestAsHex((userLoginDTO.getPassword()+PasswordConstant.SALT).getBytes());
        if (!passwordIn.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        // 人存在，密码也正确，返回结果
        // 需要token
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        // 返回值
        UserLoginVo userLoginVo = UserLoginVo.builder()
                .id(user.getId())
                .name(user.getName())
                .token(token)
                .build();
        return userLoginVo;
    }

    @Override
    public UserVo insert(UserDto userDto) {
        log.info("传入的用户为:{}",userDto);
        // 判断用户是否已经存在
        User user1 = userMapper.queryByPhone(userDto.getPhone());
        if(user1 != null){
            throw new BaseException(MessageConstant.ALREADY_EXITS);
        }
        User user = new User();
        // 到这里账号不存在存在
        BeanUtils.copyProperties(userDto,user);
        user.setStatus(1);
        // 对密码进行加密
        String pass = user.getPassword() + PasswordConstant.SALT;
        user.setPassword(DigestUtils.md5DigestAsHex(pass.getBytes()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
        UserVo resp = new UserVo();
        BeanUtils.copyProperties(user,resp);
        return resp;
    }

    @Override
    public UserVo edit(EditUserDto editUserDto) {
        // 修改用户的信息，除了id和密码，密码单独修改
        // 首先查询用户是否存在
        User user = userMapper.selectByPrimaryKey(editUserDto.getId());
        if (user == null){
            throw new BaseException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        // 到这里就一致了
        user.setStatus(editUserDto.getStatus());
        user.setName(editUserDto.getName());
        user.setPhone(editUserDto.getPhone());
        user.setUpdateTime(LocalDateTime.now());
        log.info("查询出来的用户为{}",user);
        userMapper.updateByPrimaryKey(user);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        return userVo;
    }

    @Override
    public void editPass(EditPassDto editPassDto) {
        // 首先查询是否存在
        User user = userMapper.selectByPrimaryKey(editPassDto.getId());
        if (user == null){
            throw new BaseException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        // 然后对查询出来的用户进行密码的修改
        String newPass = DigestUtils.md5DigestAsHex((editPassDto.getPassword() + PasswordConstant.SALT).getBytes());
        user.setPassword(newPass);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateByPrimaryKey(user);
    }

    @Override
    public PageResult pageQuery(Integer page, Integer size, String name) {
        PageHelper.startPage(page, size);
        UserPageDto userPageDto = new UserPageDto();
        userPageDto.setPage(page);
        userPageDto.setSize(size);
        userPageDto.setName(name);
        log.info("传入的参数为{}",userPageDto);
        log.info("要查找的名字为{}",name);
        Page<UserVo> userPage = userMapper.pageQuery(name);
        long total = userPage.getTotal();
        List<UserVo> records = userPage.getResult();
        return new PageResult(total, records);
    }

    @Override
    public void detelt(Integer id) {
        userMapper.deleteByPrimaryKey(Long.valueOf(id));
    }

    @Override
    public User getById(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        user.setPassword("****");
        return user;
    }
}
